package com.tqz.juc.aqs;

import java.util.concurrent.Exchanger;

/**
 * 两个线程之间的交换.
 *
 * @author tianqingzhao
 * @since 2022/2/5 18:17
 */
public class ExchangerTest {

    public static void main(String[] args) {

        final Exchanger<Integer> exchanger = new Exchanger<Integer>();
        for (int i = 0; i < 10; i++) {
            final Integer num = i;
            new Thread() {
                public void run() {
                    System.out.println("我是线程：Thread_" + this.getName() + "我的数据是：" + num);
                    try {
                        // 如果另外一个线程没有调用 exchange方法，那么当前线程就会一直阻塞在这里
                        Integer exchangeNum = exchanger.exchange(num);
                        Thread.sleep(1000);
                        System.out.println("我是线程：Thread_" + this.getName() + "我原先的数据为：" + num + " , 交换后的数据为：" + exchangeNum);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }
    }

}
